var cheerio = require('cheerio');
var fs = require('fs');
var lib = require('../../lib/index.js');
var config = require('./detailConfig.json');

// 1.创建数据链接
var connection = lib.connectionMDC();
connection.on('error', function(err) {
    console.log('db error', err);
    if (err.code === 'PROTOCOL_CONNECTION_LOST') {
        connection = lib.connectionMDC();
    } else {
        throw err;
    }
});

// 监听父进程消息
process.on('message', (msg) => {
  console.log(msg);
});

querySql();

function endProgram() {
    console.log('中止程序,准备重启');

    fs.writeFile('./detailConfig.json', JSON.stringify(config), function(err) {
        if (err) {
            console.log(err);
        }else{
            console.log('中止程序前配置文件保存成功');
            process.exit(0);//主动中止程序
        }
    });
}

async function querySql() {
    // 延迟执行往后的程序
    // await lib.wait(500);

    var sql = "select supplyName,productsUrl from mdc_supplys"+config.tableIndex+"_"+config.tableIndex2+"  limit "+config.queryParam.start+",1;";
    // console.log(sql);
    connection.query(sql,async function(err, result) {
        if (err) {
            console.log(err);
            return;
        }
        var data = result[0];
        if(!data){
            console.log('mdc_supplys'+config.tableIndex+'_'+config.tableIndex2+'表采集结束,5s后采集下一张表');
            console.log('-----------end-----------');
            console.log();
            console.log();
            console.log();
            config.tableIndex2++;
            config.queryParam.start = 0;
            config.page=1;

            await lib.wait(5000);

            querySql();
            return false;
        }
        lib.creditMdcProductTable(connection,'mdc_supplys'+config.tableIndex+'_'+config.tableIndex2+'_products');

        var pos = data.productsUrl.indexOf('product-list');
        var pos2 = data.productsUrl.indexOf('product-list/catalog');
        var url;

        if(pos > -1){
            url = data.productsUrl.substr(0,pos) + 'product-list-' + config.page + '.html';
        }
        if(pos2 > -1){
            url = data.productsUrl.substr(0,pos) + 'product-list/catalog-' + config.page + '.html';
        }

        // console.log(url);
        // return false;
        getList({
            supplyName:data.supplyName,
            productsUrl:url
        });
    });
}

async function getList(data) {
    console.log('-----------'+ lib.getTime() +'-----------');
    console.log('mdc_supplys'+config.tableIndex+'_'+config.tableIndex2+',第'+config.queryParam.start+'条记录采集中...');
    console.log('list:'+data.productsUrl);
    // 根据企业名查询
    let result1 = await lib.myRequest(data.productsUrl).catch((e)=>{
        console.log(e);
        return false;
    });
    if(!result1){
        endProgram();
        return false;
    }

    var $ = cheerio.load(result1);
    var info = $('.font16px').text().trim();
    if(info.indexOf('We are sorry that this showroom')>-1){
        console.log('此商家的产品列表不存在 跳过');
        console.log();
        console.log();
        config.queryParam.start++;
        config.page=1;
        querySql();
        return false;
    }

    var promiseArr = [];
    var style = 1;
    // 风格1
    $('.product-list .prod-item-wrap .prod-item').each(function (index) {
        var productName = $(this).find('.prod-name a').text().trim();
        var url = $(this).find('.prod-name a').attr('href');

        var promiseFun = new Promise((resolve, reject) => {
            setTimeout(function () {
                getDetail({
                    productName:productName,
                    url:url,
                    supplyName:data.supplyName,
                    index:index
                },resolve, reject);
            }, 100*index);
        });
        promiseArr.push(promiseFun);
    });


    // 风格2
    if(promiseArr.length <=0){
        style = 2;

        $('.prod-result-item').each(function (index) {
            var productName = $(this).find('.prod-title a').text().trim();
            var url = $(this).find('.prod-title a').attr('href');

            var promiseFun = new Promise((resolve, reject) => {
                setTimeout(function () {
                    getDetail({
                        productName:productName,
                        url:url,
                        supplyName:data.supplyName,
                        index:index
                    },resolve, reject);
                }, 100*index);
            });
            promiseArr.push(promiseFun);
        });
    }

    // 风格3
    if(promiseArr.length <=0){
        style = 3;

        $('.list-wrap .item').each(function (index) {
            var productName = $(this).find('.pro-name a').text().trim();
            var url = $(this).find('.pro-name a').attr('href');

            var promiseFun = new Promise((resolve, reject) => {
                setTimeout(function () {
                    getDetail({
                        productName:productName,
                        url:url,
                        supplyName:data.supplyName,
                        index:index
                    },resolve, reject);
                }, 100*index);
            });
            promiseArr.push(promiseFun);
        });
    }

    if(style == 1){
        config.page = $('.pager .current').text() || 1;
        console.log('当前:'+config.page);
    }else if(style == 2){
        var max = $('.prod-result-options .page-number').text().trim();
        console.log('当前:'+max);
        if(max){
            config.page = max.split('/')[0];
        }else{
            config.page = 1;
        }
        // console.log(config.page);
        // return false;
    }else if(style == 3){
        config.page = $('.pager .page-num strong').eq(0).text() || 1;
        console.log('当前:'+config.page);
    }
    console.log('列表风格'+style);

    // return false;
    if(promiseArr.length <=0){
        console.log('页面被屏蔽');
        endProgram();
        return false;
    }

    if(config.page > 5){
        console.log('商品页太多 只采集前4页数据');
        // 下一企业产品
        config.queryParam.start++;
        config.page=1;
        querySql();
        return false;
    }

    Promise.all(promiseArr).then((values) => {
        for(var i=0;i<values.length;i++){
            var item = values[i];
            // console.log('产品'+i+',返回状态:'+item.code);
            console.log(item.code);
            if(item.code == 200){
                // if(i == 0){
                //     console.log(item);
                // }
                // 插入数据
                lib.insertData(connection,'mdc_supplys'+config.tableIndex+'_'+config.tableIndex2+'_products',item.data);
            }
        }
        // return false;

        var nextUrl = $('.pager .next').attr('href');
        if(nextUrl){
            console.log('有下一页');
            console.log();
            console.log();

            // 下一页
            getList({
                supplyName:data.supplyName,
                productsUrl:nextUrl,
            });
        }else{
            console.log('当前公司产品采集完毕');
            console.log();
            console.log();

            // 下一企业产品
            config.queryParam.start++;
            config.page=1;
            querySql();
        }
    }).catch((e)=>{
        console.log('promise.all Err');
        console.log(e);
    });
}

// 产品内容
async function getDetail(detailItem,resolve,reject) {
    let detailResult = await lib.myRequest(detailItem.url).catch((e)=>{
        console.log(e);
        return false;
    });
    if(!detailResult){
        endProgram();
        return false;
    }

    let $ = cheerio.load(detailResult);

    var detail = {};
    detail.productName = detailItem.productName;
    detail.supplyName = detailItem.supplyName;

    // 所在目录
    var fullCategory = [];
    $('.sr-crumb span a').each(function () {
        fullCategory.push($(this).text().trim());
    });
    detail.fullCategory = fullCategory.join('>');

    // 判断图片
    let imgs = [];
    $('.sr-proMainInfo-slide-pageUl li').each(function () {
        let src = $(this).find('img').data('original').replace(/200/g,'202');
        imgs.push(src);
    });
    if(imgs.length == 0){
        let src = $('.page-product-details .gallary-box .pic-list .hvalign img').attr('src');
        imgs.push(src);
    }
    detail.imgs = imgs.toString();

    // detail.video = $('.sr-proMainInfo-baseInfo .J-baseInfo-name').text().trim();
    let videoSrc = $('.play-mark').next().html();
    let videoImg = $('.J-play-video-btn img').attr('src');
    detail.videoSrc = ''
    detail.videoImg = ''
    if(videoSrc){
        detail.videoSrc = videoSrc
    }
    if(videoImg){
        detail.videoImg = videoImg
    }

    let attr = {};
    $('.sr-proMainInfo-baseInfo-propertyAttr tr').each(function () {
        let key = $(this).find('th').text().replace(':','').replace(/\s/g,'_');
        let value = $(this).find('td').text().trim();
        attr[key] = value
    });
    detail.attr = JSON.stringify(attr);
    let baseInfo = {};
    $('.basic-info-list .bsc-item').each(function () {
        let key = $(this).find('.bac-item-label').text();
        let value = $(this).find('.bac-item-value').text().trim();
        baseInfo[key] = value
    });
    detail.baseInfo = JSON.stringify(baseInfo);
    detail.richText = $('.rich-text').html();
    detail.url = detailItem.url;

    resolve({
        code:200,
        data:detail
    })
}
